<template>
  <div>
    <el-button slot="reference" @click="goBack">返回</el-button>
    <el-button slot="reference" @click="inputData">导入数据</el-button>
    <el-table :data="tableData">
      <el-table-column prop="checkTime" label="日期" width="140" :formatter="formatDate">
      </el-table-column>
      <el-table-column label="姓名" width="140">
        <template slot-scope="scope">
          {{adminName}}
        </template>
      </el-table-column>
      <el-table-column  label="楼栋" width="140">
        <template slot-scope="scope">
          {{buildingName}}
        </template>
      </el-table-column>
      <el-table-column prop="roomName" label="房间" width="140">
      </el-table-column>
      <el-table-column prop="grade" label="分数" width="140">
      </el-table-column>
      <el-table-column label="操作" width="140">
        <template slot-scope="scope">
          <el-button
              size="small"
              type="primary"
              @click="modifyGrade(scope.row)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageNo"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total=totalNum>
      </el-pagination>
    </div>
    <el-dialog title="导入数据" :visible.sync="inputDataVisible">
      <div style="display: flex; justify-content: space-between;">
        <el-upload action="#" :auto-upload="false" :on-change="handleFileSelect" accept=".xls,.xlsx">
          <el-button type="primary">上传excel</el-button>
        </el-upload>
        <el-button type="primary" @click="sendUpdateGradeList">确认上传</el-button>
      </div>
      <el-table ref="table" :data="dataList">
        <el-table-column label="楼栋" prop="buildingName"></el-table-column>
        <el-table-column label="房间" prop="roomName"></el-table-column>
        <el-table-column label="分数" prop="grade"></el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="编辑分数" :visible.sync="dialogFormVisible">
      <el-form >
        <el-form-item prop="date" label="日期:" width="140">
          {{formattedcheckTime}}
        </el-form-item>
        <el-form-item prop="building" label="楼栋:" width="120">
          {{editTable.buildingName}}
        </el-form-item>
        <el-form-item prop="room" label="房间:" width="120">
          {{editTable.roomName}}
        </el-form-item>
        <el-form-item prop="grade" label="分数:" width="120">
          <el-input v-model="editTable.grade"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendUpdateGrade">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as xlsx from 'xlsx'
import {getOneActivity, updateGrade, updateGradeList} from '../../../api/dormitory_admin'

export default {
  data () {
    return {
      pageNo: 1,
      pageSize: 5,
      totalNum: 0,
      buildingName: JSON.parse(localStorage.getItem('buildingName')).name,
      adminName: JSON.parse(localStorage.getItem('user')).name,
      inputDataVisible: false,
      dialogTableVisible: false,
      dialogFormVisible: false,
      DOT: {
        pageNo: 1,
        pageSize: 5,
        data: {
          ID: JSON.parse(localStorage.getItem('user')).id.toString(),
          checkTime: this.$route.query.checkTime
        }
      },
      editTable: {
        id: null,
        checkTime: '',
        buildingName: '',
        roomName: '',
        grade: null
      },
      tableData: [],
      dataList: []
    }
  },
  methods: {
    formatDate (row) {
      const date = new Date(row.checkTime)
      const beijingTime = new Date(date.getTime())
      const year = beijingTime.getFullYear()
      const month = (beijingTime.getMonth() + 1).toString().padStart(2, '0')
      const day = beijingTime.getDate().toString().padStart(2, '0')
      return `${year}年${month}月${day}日`
    },
    handleFileSelect (event) {
      const file = event.raw
      const reader = new FileReader()
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result)
        const workbook = xlsx.read(data, { type: 'array' })
        const worksheet = workbook.Sheets[workbook.SheetNames[0]]
        const jsonData = xlsx.utils.sheet_to_json(worksheet, { header: 1 })
        let headers = jsonData[1]
        jsonData.slice(2).forEach(row => {
          const rowData = row.reduce((accumulator, item, index) => {
            let column = headers[index]
            if (typeof item === 'number' && headers[index].toLowerCase().includes('date')) {
              const date = xlsx.SSF.parse_date_code(item)
              accumulator[column] = `${date.y}-${date.m}-${date.d}`
            } else {
              accumulator[column] = item
            }
            return accumulator
          }, {})
          this.dataList.push(rowData)
        })
      }
      reader.readAsArrayBuffer(file)
    },
    inputData () {
      this.inputDataVisible = true
    },
    goBack () {
      this.$router.push('/dormitory_admin/HygieneManagement')
    },
    modifyGrade (row) {
      this.editTable = JSON.parse(JSON.stringify(row))
      this.editTable.buildingName = this.buildingName
      this.dialogFormVisible = true
    },
    handleCurrentChange (newPage) {
      this.DOT.pageNo = newPage
      this.pageNo = newPage
      this.getInformation()
    },
    sendUpdateGrade () {
      this.dialogFormVisible = false
      let obj = []
      obj.push({id: String(this.editTable.id), grade: this.editTable.grade})
      updateGrade(obj).then(res => {
        this.$message({
          message: '修改成功',
          type: 'success'
        })
        this.getInformation()
      })
    },
    sendUpdateGradeList () {
      let obj = {
        dormitoryAdminID: String(JSON.parse(localStorage.getItem('user')).id),
        checkTime: this.$route.query.checkTime,
        dataList: this.dataList
      }
      updateGradeList(obj).then(res => {
        this.$message({
          message: '修改成功',
          type: 'success'
        })
        this.getInformation()
      })
      this.inputDataVisible = false
    },
    getInformation () {
      getOneActivity(this.DOT).then(res => {
        this.totalNum = res.otherData.totalNum
        this.tableData = res.data
      })
    }
  },
  computed: {
    formattedcheckTime () {
      const date = new Date(this.editTable.checkTime)
      const beijingTime = new Date(date.getTime() + 8 * 60 * 60 * 1000)
      const year = beijingTime.getFullYear()
      const month = (beijingTime.getMonth() + 1).toString().padStart(2, '0')
      const day = beijingTime.getDate().toString().padStart(2, '0')
      return `${year}年${month}月${day}日`
    }
  },
  created () {
    this.getInformation()
  }
}
</script>
<style scoped>
</style>
